
const _interopRequireDefault = require('@babel/runtime/helpers/interopRequireDefault');

exports.__esModule = true;
exports.default = void 0;

const _extends2 = _interopRequireDefault(require('@babel/runtime/helpers/extends'));

const _utils = require('../utils');

const _event = require('../utils/dom/event');

const _constant = require('../utils/constant');

const _shared = require('./shared');

const _loading = _interopRequireDefault(require('../loading'));

const _PickerColumn = _interopRequireDefault(require('./PickerColumn'));

// Utils
// Components
const _createNamespace = (0, _utils.createNamespace)('picker');
const createComponent = _createNamespace[0];
const bem = _createNamespace[1];
const t = _createNamespace[2];

const _default2 = createComponent({
  props: (0, _extends2.default)({}, _shared.pickerProps, {
    defaultIndex: {
      type: [Number, String],
      default: 0,
    },
    columns: {
      type: Array,
      default: function _default() {
        return [];
      },
    },
    toolbarPosition: {
      type: String,
      default: 'top',
    },
    valueKey: {
      type: String,
      default: 'text',
    },
  }),
  data: function data() {
    return {
      children: [],
      formattedColumns: [],
    };
  },
  computed: {
    dataType: function dataType() {
      const { columns } = this;
      const firstColumn = columns[0] || {};

      if (firstColumn.children) {
        return 'cascade';
      }

      if (firstColumn.values) {
        return 'object';
      }

      return 'text';
    },
  },
  watch: {
    columns: {
      handler: 'format',
      immediate: true,
    },
  },
  methods: {
    format: function format() {
      const { columns } = this;
      const { dataType } = this;

      if (dataType === 'text') {
        this.formattedColumns = [{
          values: columns,
        }];
      } else if (dataType === 'cascade') {
        this.formatCascade();
      } else {
        this.formattedColumns = columns;
      }
    },
    formatCascade: function formatCascade() {
      const _this = this;

      const formatted = [];
      let cursor = {
        children: this.columns,
      };

      while (cursor && cursor.children) {
        const defaultIndex = cursor.defaultIndex || +this.defaultIndex;
        formatted.push({
          values: cursor.children.map((item) => item[_this.valueKey]),
          className: cursor.className,
          defaultIndex,
        });
        cursor = cursor.children[defaultIndex];
      }

      this.formattedColumns = formatted;
    },
    emit: function emit(event) {
      if (this.dataType === 'text') {
        this.$emit(event, this.getColumnValue(0), this.getColumnIndex(0));
      } else {
        this.$emit(event, this.getValues(), this.getIndexes());
      }
    },
    onCascadeChange: function onCascadeChange(columnIndex) {
      let cursor = {
        children: this.columns,
      };
      const indexes = this.getIndexes();

      for (let i = 0; i <= columnIndex; i++) {
        cursor = cursor.children[indexes[i]];
      }

      while (cursor && cursor.children) {
        columnIndex++;
        this.setColumnValues(columnIndex, cursor.children);
        cursor = cursor.children[cursor.defaultIndex || 0];
      }
    },
    onChange: function onChange(columnIndex) {
      if (this.dataType === 'cascade') {
        this.onCascadeChange(columnIndex);
      }

      if (this.dataType === 'text') {
        this.$emit('change', this, this.getColumnValue(0), this.getColumnIndex(0));
      } else {
        this.$emit('change', this, this.getValues(), columnIndex);
      }
    },
    // get column instance by index
    getColumn: function getColumn(index) {
      return this.children[index];
    },
    // @exposed-api
    // get column value by index
    getColumnValue: function getColumnValue(index) {
      const column = this.getColumn(index);
      return column && column.getValue();
    },
    // @exposed-api
    // set column value by index
    setColumnValue: function setColumnValue(index, value) {
      const column = this.getColumn(index);

      if (column) {
        column.setValue(value);

        if (this.dataType === 'cascade') {
          this.onCascadeChange(index);
        }
      }
    },
    // @exposed-api
    // get column option index by column index
    getColumnIndex: function getColumnIndex(columnIndex) {
      return (this.getColumn(columnIndex) || {}).currentIndex;
    },
    // @exposed-api
    // set column option index by column index
    setColumnIndex: function setColumnIndex(columnIndex, optionIndex) {
      const column = this.getColumn(columnIndex);

      if (column) {
        column.setIndex(optionIndex);

        if (this.dataType === 'cascade') {
          this.onCascadeChange(columnIndex);
        }
      }
    },
    // @exposed-api
    // get options of column by index
    getColumnValues: function getColumnValues(index) {
      return (this.children[index] || {}).options;
    },
    // @exposed-api
    // set options of column by index
    setColumnValues: function setColumnValues(index, options) {
      const _this2 = this;

      const column = this.children[index];

      if (column) {
        if (this.dataType === 'cascade') {
          // map should be removed in next major version
          column.setOptions(options.map((item) => ((0, _utils.isObject)(item) ? item[_this2.valueKey] : item)));
        } else {
          column.setOptions(options);
        }
      }
    },
    // @exposed-api
    // get values of all columns
    getValues: function getValues() {
      return this.children.map((child) => child.getValue());
    },
    // @exposed-api
    // set values of all columns
    setValues: function setValues(values) {
      const _this3 = this;

      values.forEach((value, index) => {
        _this3.setColumnValue(index, value);
      });
    },
    // @exposed-api
    // get indexes of all columns
    getIndexes: function getIndexes() {
      return this.children.map((child) => child.currentIndex);
    },
    // @exposed-api
    // set indexes of all columns
    setIndexes: function setIndexes(indexes) {
      const _this4 = this;

      indexes.forEach((optionIndex, columnIndex) => {
        _this4.setColumnIndex(columnIndex, optionIndex);
      });
    },
    // @exposed-api
    confirm: function confirm() {
      this.children.forEach((child) => child.stopMomentum());
      this.emit('confirm');
    },
    cancel: function cancel() {
      this.emit('cancel');
    },
    genTitle: function genTitle() {
      const h = this.$createElement;
      const titleSlot = this.slots('title');

      if (titleSlot) {
        return titleSlot;
      }

      if (this.title) {
        return h('div', {
          class: ['van-ellipsis', bem('title')],
        }, [this.title]);
      }
    },
    genToolbar: function genToolbar() {
      const h = this.$createElement;

      if (this.showToolbar) {
        return h('div', {
          class: [_constant.BORDER_TOP_BOTTOM, bem('toolbar')],
        }, [this.slots() || [h('button', {
          attrs: {
            type: 'button',
          },
          class: bem('cancel'),
          on: {
            click: this.cancel,
          },
        }, [this.cancelButtonText || t('cancel')]), this.genTitle(), h('button', {
          attrs: {
            type: 'button',
          },
          class: bem('confirm'),
          on: {
            click: this.confirm,
          },
        }, [this.confirmButtonText || t('confirm')])]]);
      }
    },
    genColumns: function genColumns() {
      const _this5 = this;

      const h = this.$createElement;
      return this.formattedColumns.map((item, columnIndex) => h(_PickerColumn.default, {
        attrs: {
          valueKey: _this5.valueKey,
          allowHtml: _this5.allowHtml,
          className: item.className,
          itemHeight: _this5.itemHeight,
          defaultIndex: item.defaultIndex || +_this5.defaultIndex,
          swipeDuration: _this5.swipeDuration,
          visibleItemCount: _this5.visibleItemCount,
          initialOptions: item.values,
        },
        on: {
          change: function change() {
            _this5.onChange(columnIndex);
          },
        },
      }));
    },
  },
  render: function render(h) {
    const itemHeight = +this.itemHeight;
    const wrapHeight = itemHeight * this.visibleItemCount;
    const frameStyle = {
      height: `${itemHeight}px`,
    };
    const columnsStyle = {
      height: `${wrapHeight}px`,
    };
    const maskStyle = {
      backgroundSize: `100% ${(wrapHeight - itemHeight) / 2}px`,
    };
    return h('div', {
      class: bem(),
    }, [this.toolbarPosition === 'top' ? this.genToolbar() : h(), this.loading ? h(_loading.default, {
      class: bem('loading'),
    }) : h(), this.slots('columns-top'), h('div', {
      class: bem('columns'),
      style: columnsStyle,
      on: {
        touchmove: _event.preventDefault,
      },
    }, [this.genColumns(), h('div', {
      class: bem('mask'),
      style: maskStyle,
    }), h('div', {
      class: [_constant.BORDER_UNSET_TOP_BOTTOM, bem('frame')],
      style: frameStyle,
    })]), this.slots('columns-bottom'), this.toolbarPosition === 'bottom' ? this.genToolbar() : h()]);
  },
});

exports.default = _default2;
